package com.sh.suhe.utildemos.utils.socket.entity;

import com.sh.suhe.utildemos.model.Message;
import com.sh.suhe.utildemos.model.PDAData;
import com.sh.suhe.utildemos.utils.JsonUtil;
import com.sh.suhe.utildemos.utils.LogUtil;

public class SocketPacket {
    private static final String sCharset = "UTF-8";
    //请求id
    private int iRequestId = 0;
    //请求数据
    private RequestPacket requestPacket;
    //返回数据
    private ResponsePacket responsePacket;

    public SocketPacket() {
    }
    public void setRequestPacket(Object reqData){
        requestPacket = new RequestPacket(reqData);
    }


    public int getRequestId() {
        return iRequestId;
    }

    public void setRequestId(int iRequestId) {
        this.iRequestId = iRequestId;
        requestPacket.setRequestId(iRequestId);
    }

    public void setResponsePacket(byte[] rp) {
        this.responsePacket = new ResponsePacket();
        this.responsePacket.setBuffer(rp);
        decode(rp);
    }
    public Object getResponseData(){
        if (this.responsePacket != null) {
            return this.responsePacket.getData();
        }else {
            return null;
        }
    }

    public byte[] encode() {
        if (requestPacket != null) {
            return requestPacket.encode();
        }
        return new byte[0] ;
    }
    public void decode(byte[] rspBytes) {
        try {
            String data = new String(rspBytes,sCharset);
            data = data.trim();
            Message msg = JsonUtil.json2Object(data, Message.class);
            if (msg!= null){
                this.iRequestId = msg.getReqId();
            }
        }catch (Exception e){
            LogUtil.e("ReponsePacket","解析失败："+e.getLocalizedMessage());
        }
    }

    public void read(Class<PDAData> pdaDataClass) {
        this.responsePacket.read(pdaDataClass);
    }
}
